package com.spacing.app;

import java.util.Arrays;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.view.View.OnKeyListener;
import android.view.Window;
import android.view.inputmethod.InputMethodManager;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.spacing.app.data.Chapters;
import com.spacing.app.Spacer;

public class QuizActivity extends Activity {
	static final String[] letters = new String[] { "A", "B", "C", "D", "E",
			"F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R",
			"S", "T", "U", "V", "W", "X", "Y", "Z" };
	Integer[] order = { 0, 1, 2, 3 };
	Question q;
	Button[] buttons;
	TextView hint_tv;
	TextView answer_tv;
	Chapters chapters;
	Spacer spacer;
	int chapter;
	int section;
	Button next;
	String word;
	String word_compare;
	String[] answer;
	String answer_str;
	int number_of_correct;
	ArrayAdapter<String> adapter;
	static final String[] special_char = new String[] { " ", "!", "@", "#",
			"$", "%", "^", "&", "*", "(", ")", "?", ":", ";", ",", "." };
	EditText input;
	TextView score;
	int count_wrong;
	int count_correct;
	

	static boolean bool = true;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		requestWindowFeature(Window.FEATURE_NO_TITLE);
	    this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);

		super.onCreate(savedInstanceState);
		setContentView(R.layout.typeit);
		adapter = new ArrayAdapter<String>(this,
				android.R.layout.simple_list_item_1, letters);

		Intent intent = getIntent();
		chapters = (Chapters) intent.getSerializableExtra("chapters");
		chapter = (int) intent.getExtras().getInt("chapter");
		section = (int) intent.getExtras().getInt("section");
		spacer = new Spacer(chapters.get(chapter).get(section).getWords(), new SchemaHelper(this));
		q = new Question(chapters, chapter, section, spacer, false);
		hint_tv = (TextView) findViewById(R.id.hint);
		answer_tv = (TextView) findViewById(R.id.answer);
		
		next.setEnabled(false);
		input = (EditText) findViewById(R.id.editText1);
		setQuestion();
		bool = true;
		count_wrong = 0;
		count_correct = 0;

		input.setOnKeyListener(new OnKeyListener() {
			public boolean onKey(View v, int keyCode, KeyEvent event) {
				System.out.println(keyCode);

				if ((event.getAction() == KeyEvent.ACTION_DOWN)
						&& (keyCode == KeyEvent.KEYCODE_ENTER)) {
					return true;
				} else if ((event.getAction() == KeyEvent.ACTION_UP)
						&& keyCode == KeyEvent.KEYCODE_ENTER) {
					// your additional processing...
					if (!bool) {
						bool = true;
						clickNext();
						return true;
					}

					next.setEnabled(true);
					checkAnswer();
					bool = false;
					return true;
				}

				return false;
			}
		});

	}

	private void setQuestion() {
		if (q.nextQuestion()) {
			word = q.questions[0][0];
			word_compare = removeAccents(q.questions[0][0].toUpperCase());
			hint_tv.setText(q.questions[1][0]);// + " " + word);
			answer = new String[word.length()];
			Arrays.fill(answer, "__");
			number_of_correct = 0;

			input.setTextColor(getResources().getColor(R.color.black));
			input.setBackgroundColor(getResources().getColor(R.color.white));
			input.setText("");

			spacer.startOfEventTime = System.currentTimeMillis(); 
			// Set the start of event time. This is needed if the answer is incorrect.

		} else {
			InputMethodManager imm = (InputMethodManager)getSystemService(
				      Context.INPUT_METHOD_SERVICE);
				imm.hideSoftInputFromWindow(input.getWindowToken(), 0);
			setContentView(R.layout.score);
			score = (TextView)findViewById(R.id.textViewScore);
			int count_total = count_correct+count_wrong; 
			score.setText("Score: "+count_correct+"/"+count_total);
		}
	}

	public void clickNext(View view) {
		bool = true;
		setQuestion();
		next.setEnabled(false);
	}

	public void clickNext() {
		setQuestion();
		next.setEnabled(false);
	}

	private static final String PLAIN_ASCII = "AaEeIiOoUu" // grave
			+ "AaEeIiOoUuYy" // acute
			+ "AaEeIiOoUuYy" // circumflex
			+ "AaOoNn" // tilde
			+ "AaEeIiOoUuYy" // umlaut
			+ "Aa" // ring
			+ "Cc" // cedilla
			+ "OoUu" // double acute
	;

	private static final String UNICODE = "\u00C0\u00E0\u00C8\u00E8\u00CC\u00EC\u00D2\u00F2\u00D9\u00F9"
			+ "\u00C1\u00E1\u00C9\u00E9\u00CD\u00ED\u00D3\u00F3\u00DA\u00FA\u00DD\u00FD"
			+ "\u00C2\u00E2\u00CA\u00EA\u00CE\u00EE\u00D4\u00F4\u00DB\u00FB\u0176\u0177"
			+ "\u00C3\u00E3\u00D5\u00F5\u00D1\u00F1"
			+ "\u00C4\u00E4\u00CB\u00EB\u00CF\u00EF\u00D6\u00F6\u00DC\u00FC\u0178\u00FF"
			+ "\u00C5\u00E5" + "\u00C7\u00E7" + "\u0150\u0151\u0170\u0171";

	/**
	 * remove accented from a string and replace with ascii equivalent
	 */
	public static String removeAccents(String s) {
		if (s == null)
			return null;
		StringBuilder sb = new StringBuilder(s.length());
		int n = s.length();
		int pos = -1;
		char c;
		boolean found = false;
		for (int i = 0; i < n; i++) {
			pos = -1;
			c = s.charAt(i);
			pos = (c <= 126) ? -1 : UNICODE.indexOf(c);
			if (pos > -1) {
				found = true;
				sb.append(PLAIN_ASCII.charAt(pos));
			} else {
				sb.append(c);
			}
		}
		if (!found) {
			return s;
		} else {
			return sb.toString();
		}
	}

	public void correctAnswer() {
		count_correct++;
		input.setTextColor(getResources().getColor(R.color.green));
		input.setBackgroundColor(getResources().getColor(R.color.lightgreen));
		input.setText(q.questions[0][0]);
		spacer.updateAnswer(true, getCurrentTime());
	}

	public void wrongAnswer() {
		count_wrong++;
		input.setTextColor(getResources().getColor(R.color.red));
		input.setBackgroundColor(getResources().getColor(R.color.lightred));
		input.setText(q.questions[0][0]);
		spacer.updateAnswer(false, getCurrentTime());
	}

	public void checkAnswer() {
		String answer = input.getText().toString();
		answer = removeAccents(answer);
		answer = answer.toLowerCase();
		answer = answer.trim();
		answer = answer.replaceAll(",", "");

		String correct_answer = q.questions[0][0];
		correct_answer = removeAccents(correct_answer);
		correct_answer = correct_answer.toLowerCase();
		correct_answer = correct_answer.replaceAll(",", "");
		correct_answer = correct_answer.trim();
		if (answer.equals(correct_answer)) {

			correctAnswer();

		} else {
			/*
			 * Toast toast = Toast.makeText(this, "Wrong!" ,
			 * Toast.LENGTH_SHORT); toast.setGravity(Gravity.CENTER_VERTICAL, 0,
			 * 0); toast.show();
			 */

			wrongAnswer();
		}

	}

	public long getCurrentTime() {
		return System.currentTimeMillis();
	}
	
	public void clickDone(View v){
		
		finish();
		
	}

}